<template>
  <div>
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" :labelWidth="100" :collapse="false" @onCollapse="collapseHandle" @filterChange="handleFilterChange" />
    <FilterTable
      ref="mainTable"
      :fetchapi="fetchapi"
      :params="fetchParams"
      :columns="tableColumns"
      columnsRef="aduitOrder"
      :datakey="'records'"
      :onRowSelectChange="handleRowSelectChange"
      :onColumnsChange="columns => (this.tableColumns = columns)"
      :isExportExcel2="true"
      :exportFileName="'采购单清单.xlsx'"
    >
      <!-- <template slot="controls" slot-scope="props">
        <el-switch
          @change="aotoAuditOrderSwitchChange"
          v-model="aotoAuditOrderSwitch"
          active-text="自动审单"
          inactive-text="手动审单">
        </el-switch>
      </template> -->
    </FilterTable>
    <div>
      <Drawer width="100%" title="采购单明细" :visible.sync="isShowpartBuyItems" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <partBuyItems :top="top" @cancel="cancel" />
      </Drawer>
    <BaseDialog
      :visible.sync="issearch"
      :title="'服务商查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ownerSeacher  @close="dealercloseHandler" />
    </BaseDialog>
    </div>
  </div>
</template>

<script>
import { queryPartBuyCheck,autoAuditOrderSwitchFuc} from '@/api/partsmanage/aduitOrder/index';
import { dictionary } from '@/utils/dictMixin';
import SearchCustomer from './SearchCustomer';
import partBuyItems from './partBuyItems';
import ownerSeacher from '@/pages/partsmanage/claim/approve/ownerSeacher';
import {getMessageCount} from '@/api/cms-api/todoTask/view/index';
import {mapMutations} from "vuex";

export default {
  name: 'aduitOrder',
  mixins: [dictionary],
  components: {
    partBuyItems,
    SearchCustomer,
    ownerSeacher
  },
  data() {
    return {
      aotoAuditOrderSwitch:false,
      top: {},
      rowData: {},
      selectList: [],
      topFilterList: this.createTopFilterList(),
      tableColumns: this.createTableColumns(),
      isShowpartBuyItems: false,
      fetchapi: queryPartBuyCheck,
      fetchParams: { xhrAbort: true },
      issearch: false,
    };
  },
  mounted() {
    // this.confirmSearchCustomer();
    // findAutoAuditOrder().then(res =>{
    //   if(res.resultCode == 200 ){
    //     if(res.data.status == 10011001){
    //       this.aotoAuditOrderSwitch = true;

    //     }else if(res.data.status == 10011002){
    //       this.aotoAuditOrderSwitch = false;

    //     }else{
    //       this.aotoAuditOrderSwitch = null;

    //     }
    //   }else{
    //     this.aotoAuditOrderSwitch = null;
    //   }

    // }).catch(err =>{

    // })
  },
  methods: {
    aotoAuditOrderSwitchChange(val){
      console.log(this.aotoAuditOrderSwitch);
      console.log(val);
      this.$confirm('确认改变审单方式?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
      }).then(() =>{
        autoAuditOrderSwitchFuc(this.aotoAuditOrderSwitch).then(res =>{
          console.log(res);
          if(res.resultCode == 200 ){
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          }else{
            this.$message({
              type: 'warning',
              message: res.errMsg || '操作失败!'
            });
            this.aotoAuditOrderSwitch = !val;
          }

        }).catch(err =>{
          this.$message({
            type: 'warning',
            message: err.errMsg || '操作失败!'
          });
          this.aotoAuditOrderSwitch = !val;
        })

      }).catch(err =>{
        this.$message({
          type: 'warning',
          message: '已取消!'
        });
        this.aotoAuditOrderSwitch = !val;
      })
    },
    ...mapMutations('noticePanel', ['SET_NP_NUM']),
    seacherFun(){
      this.issearch = true
    },
    dealercloseHandler(val){
      if(val){
        this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue=val.dealerCode;
        this.topFilterList.find(x=>x.fieldName=='dealerName').initialValue=val.dealerShortname;
      }
      this.issearch=false;
    },
    cancel(){
      this.isShowpartBuyItems = false
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '服务商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '服务商简称',
          fieldName: 'dealerName',
          placeholder: '请输入...'
        },
        {
          type: 'INPUT',
          label: '备件订单号',
          fieldName: 'purchaseCode',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'stockInType',
          itemList: this.createDictList('3003'),
          placeholder: '请选择...'
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'submStartDate|submEndDate',
          label: '提报日期',
          initialValue: [],
          dateType: 'daterange'
        },

        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'purchaseStatus',
          itemList: this.createDictList('3002',[30021001,30021005,30021009,30021010]),
          placeholder: '请选择...',
          initialValue:30021002,
          clearable:false
        },
        {
          type: 'RANGE_DATE',
          fieldName: 'auditStartDate|auditEndDate',
          label: '审核日期',
          initialValue: [],
          dateType: 'daterange'
        },
        {
          type: 'SELECT',
          label: '是否免运费',
          fieldName: 'ddmyf',
          itemList: this.createDictList('1004'),
          placeholder: '请选择...'
        },

      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          // sorter: true,
          width: 70,
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          },
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: params => {
            let disabled = false;
            if(params.row.XSDDZT != '30021002') disabled = true;
            return (
              <div>
                <el-button disabled={disabled} type="text" size="mini" onClick={() => this.showItems(params.row)}>
                  审核
                </el-button>
              </div>
            );
          }
        },
        {
          title: '服务商代码',
          dataIndex: 'DEALER_CODE',
          filter: true,
          sorter: true,
          filterType: 'input'
        },
        {
          title: '服务商简称',
          dataIndex: 'DEALER_NAME',
          filter: true,
          sorter: true,
          filterType: 'input'
        },
        {
          title: '备件订单号',
          dataIndex: 'XSDDHM',
          filter: true,
          sorter: true,
          width: 180,
          filterType: 'input'
        },
        // {
        //   title: 'SAP单号',
        //   dataIndex: 'SAP_NO',
        //   filter: true,
        //   sorter: true,
        //   filterType: 'input'
        // },
        {
          title: '订单类型',
          dataIndex: 'XSDDLX',
          filter: true,
          sorter: true,
          filterItems: this.createDictList('3003'),
          dictItems: this.createDictList('3003'),
          filterType: 'checkbox'
        },
        {
          title: '订单状态',
          dataIndex: 'XSDDZT',
          filter: true,
          sorter: true,
          filterItems: this.createDictList('3002'),
          dictItems: this.createDictList('3002'),
          filterType: 'checkbox'
        },
        {
          title: '是否免运费',
          dataIndex: 'DDMYF',
          filter: true,
          sorter: true,
          // filterItems: this.createDictList('1004'),
          dictItems: this.createDictList('1004'),
          filterType: 'checkbox'
        },

        {
          title: '订单提报日期',
          dataIndex: 'DDTBSJ',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          sorter: true,
          filterType: 'date-range'
        },
        // {
        //   title: '缺货单生成日期',
        //   dataIndex: 'OUT_OF_DATE',
        //   dateFormat: 'yyyy-MM-dd',
        //   filter: true,
        //   sorter: true,
        //   filterType: 'date-range'
        // },
        {
          title: '审核人',
          dataIndex: 'AUDIT_BY_NAME',
          filter: true,
          sorter: true,
          filterType: 'input'
        },
        {
          title: '审核日期',
          dataIndex: 'AUDIT_TIME',
          dateFormat: 'yyyy-MM-dd',
          filter: true,
          sorter: true,
          filterType: 'date-range'
        },
        {
          title: '审核说明',
          dataIndex: 'AUDIT_REM',
          filter: true,
          sorter: true,
          filterType: 'input'
        },


      ];
    },
    collapseHandle() {},
    handleFilterChange(e) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign({}, {
        ...e,
        xhrAbort: false,
        submStartDate: e.submStartDate ? e.submStartDate.split(' ')[0] : '',
        submEndDate: e.submEndDate ? e.submEndDate.split(' ')[0] : '',
        auditStartDate: e.auditStartDate ? e.auditStartDate.split(' ')[0] : '',
        auditEndDate: e.auditEndDate ? e.auditEndDate.split(' ')[0] : '',
        // dealerCode: e.customerCode ? this.rowData.dealerCode : '',
      });
    },

    async confirmSearchCustomer(row) {
      var mes = await getMessageCount();

      console.log(mes.data);
      this.SET_NP_NUM({ name: 'num', value: mes.data.number});
      console.log(row, 'rowCustomer');
      this.rowData = row[0];
      console.log('row[0].dealerCode', row[0].dealerCode);
      this.topFilterList.find(x => x.fieldName == 'customerCode').initialValue = row[0].dealerCode;
      this.topFilterList.find(x => x.fieldName == 'customerName').initialValue = row[0].dealerName;
    },
    // async translateDealer() {
    //   let res = await byAllTranslate();
    //   if (res.resultCode == 200) {
    //     // console.log(res.data, 'res.data::');
    //     let dataList = res.data ? res.data : [];
    //     // console.log(dataList, 'dataList::');
    //     let tempList = dataList.map(x => ({
    //       value: x.dealerCode,
    //       text: x.dealerName
    //     }));
    //     // console.log(tempList, 'tempList::');
    //     this.tableColumns.find(x => x.dataIndex == 'ownerCode').dictItems = tempList;
    //   }
    // },
    handleRowSelectChange(rows) {
      this.selectList = rows;
    },
    showItems(e) {
      this.isShowpartBuyItems = true;
      this.top = e;
    },

  }
};
</script>
